<template>
  <div>
    <!--    添加按钮-->
    <el-button type="primary" icon="el-icon-plus" style="margin: 10px 0px" @click="showDialog">
      添加
    </el-button>
    <!--    table表格-->
    <el-table style="width: 100%" border :data="list">
      <el-table-column label="序号" width="100px" type="index" align="center"></el-table-column>
      <el-table-column label="品牌名称" width="width" prop="tmName"></el-table-column>
      <el-table-column label="品牌logo" width="width" prop="prop">
        <template slot-scope="{row,$index}">
          <img :src="row.logoUrl" alt="" style="width: 100px;height: 100px">
        </template>
      </el-table-column>
      <el-table-column label="操作" width="width" prop="prop">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" @click="UpdateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!--    添加内容的对话框-->
    <el-dialog :title="tmFrom.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible" center>
      <el-form style="width:80%;" :model="tmFrom" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input autocomplete="off" v-model="tmFrom.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌logo" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="dev-api/admin/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmFrom.logoUrl" :src="tmFrom.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark(tmFrom)">确 定</el-button>
      </div>
    </el-dialog>
    <!--    分页器-->
    <el-pagination
      align="center"
      :background="true"
      :page-size="size"
      :page-sizes="[3,6,10]"
      :page-count="9"
      :current-page="current"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout=" prev, pager, next, jumper,sizes,-> ,total, slot"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: 'tradeMark',
  data() {
    return {
      pages: 1,//总页数
      size: 3,//页面数据条数
      list: [],//trademarkList
      current: 1,//当前页
      total: 10,//数据总条数
      //控制对话框是否展示
      dialogFormVisible: false,
      formLabelWidth: '120px',
      // //添加表单的图片地址
      // imageUrl: '',
      //对话框表单数据
      tmFrom: {
        tmName: "",
        logoUrl: "",
      },
      //表单验证规则
      rules:{
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌logo' }
        ],
      }
    }
  },
  mounted() {
    //发起trademarkList请求
    this.getList();
  },
  methods: {
    async getList() {
      //解构数据
      const {pages, current, total, size, list} = this;
      //发送请求
      const result = await this.$API.default.tradeMark.reqtradeMarkList(current, size);
      // console.log(result)
      if (result.code == 200) {
        this.pages = result.data.pages;
        this.list = result.data.records;
        this.total = result.data.total;
      }
    },
    //查看其他页
    handleCurrentChange(page) {
      this.current = page;
      this.getList();
    },
    //修改每页展示数据size
    handleSizeChange(size) {
      this.size = size;
      this.getList();
    },
    //控制对话框的展示
    showDialog(){
      this.dialogFormVisible = true;
      this.tmFrom={
        tmName: "",
        logoUrl: "",
      }
    },
    handleAvatarSuccess(res, file) {
      // console.log(res, file)
      this.tmFrom.logoUrl=res.data;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //更新或添加trademark
    addOrUpdateTradeMark(tmFrom) {
      this.dialogFormVisible = false;
      // console.log("tmFrom",tmFrom)
      this.$refs.ruleForm.validate(async (valid) => {
        // console.log("valid:",valid)
        if (valid) {
          try {
            const result = await this.$API.default.tradeMark.reqAddOrUpdateTradeMark(tmFrom);
            // console.log("addOrUpdateTradeMark",result);
            if (result.code == 200) {
              this.$message({
                message: tmFrom.id ? '修改成功' : "添加成功",
                type: 'success'
              })
            } else {
              this.$message({
                message: result.message,
                type: 'warning'
              });
            }
          } catch (e) {
            this.$message({
              message: '添加失败',
              type: 'error'
            });
          }
        } else {
          this.$message({
            message: '提交错误',
            type: 'error'
          });
          return false;
        }
      })

    //重新获取页面信息
    this.getList();
  },
    //更新TradeMark修改
    async UpdateTradeMark(tmFrom){
      this.dialogFormVisible = true;
      this.tmFrom= {...tmFrom};//浅拷贝
    },
    //删除TradeMark
    deleteTradeMark(tmFrom){
      this.$confirm(`确定删除${tmFrom.tmName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const result=await this.$API.default.tradeMark.reqDeteleTradeMark(tmFrom.id);
        // console.log("delete",result)
        if(result.code==200){
          //重新刷新页面
          this.getList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          return true;
        }else{
          //重新刷新页面
          this.getList();
          this.$message({
            type: 'warning',
            message: result.message,
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
